package com.duoec.magichour.service.impl;

import com.duoec.magichour.core.utils.UUIDUtils;
import com.duoec.magichour.dto.UserInfo;
import com.duoec.magichour.enums.AuthorizeTypeEnum;
import com.duoec.magichour.enums.RoleEnum;
import com.duoec.magichour.mapper.AuthorizeMapper;
import com.duoec.magichour.pojo.Authorize;
import com.duoec.magichour.pojo.User;
import com.duoec.magichour.service.AuthorizeService;
import com.duoec.magichour.service.UserService;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by ycoe on 17/6/29.
 */
@Service
public class AuthorizeServiceImpl implements AuthorizeService {
    @Autowired
    private AuthorizeMapper authorizeMapper;

    @Autowired
    private UserService userService;

    @Value("${user.expired.hour}")
    private int expiredHour;

    @Override
    public UserInfo get(String authToken) {
        Authorize authorize = authorizeMapper.getByToken(authToken);
        if (authorize == null) {
            return null;
        }
        if (authorize.getExpired().getTime() < System.currentTimeMillis()) {
            //已经过期
            authorizeMapper.deleteByPrimaryKey(authToken);
            return null;
        }

        Long userId = authorize.getUserId();
        UserInfo userInfo = getUserInfo(userId);
        if (userInfo == null) return null;
        userInfo.setAuthorToken(authToken);
        return userInfo;
    }

    @Override
    public UserInfo getUserInfo(Long userId) {
        User user = userService.getUser(userId);
        if (user == null) {
            return null;
        }
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user, userInfo);
        String roles = user.getRoles();
        List<RoleEnum> roleList = Lists.newArrayList();
        if (!Strings.isNullOrEmpty(roles)) {
            Splitter
                    .on(",")
                    .trimResults()
                    .omitEmptyStrings()
                    .split(roles)
                    .forEach(role -> {
                        RoleEnum r = RoleEnum.valueOf(role);
                        if (!roleList.contains(r)) {
                            roleList.add(r);
                        }
                    });
        }
        if (!roleList.contains(RoleEnum.AUTHORIZED)) {
            roleList.add(RoleEnum.AUTHORIZED);
        }
        userInfo.setRoleList(roleList);
        return userInfo;
    }

    @Override
    public Authorize mobilePwdLogin(User user) {
        Authorize authorize = authorizeMapper.getByLoginType(user.getId(), AuthorizeTypeEnum.MOBILE_PWD.getLoginType());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, expiredHour);
        Date expireTime = calendar.getTime();

        if (authorize == null) {
            authorize = new Authorize();
            authorize.setUserId(user.getId());
            authorize.setId(UUIDUtils.generateUUID());
            authorize.setAuthFrom(AuthorizeTypeEnum.MOBILE_PWD.getLoginType());
            authorize.setExpired(expireTime);
            authorize.setRoles(user.getRoles());
            authorizeMapper.insertSelective(authorize);
        } else {
            authorize.setExpired(expireTime);
            authorizeMapper.updateByPrimaryKeySelective(authorize);
        }
        return authorize;
    }

    @Override
    public void logout(UserInfo userInfo) {
        Authorize authorize = authorizeMapper.getByToken(userInfo.getAuthorToken());
        if (authorize == null) {
            return;
        }
        authorizeMapper.deleteByPrimaryKey(authorize.getId());
    }
}
